package com.k.ums.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.util.AntPathMatcher;

import javax.sql.DataSource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;

/**
 * @Description:
 * @Author: kt
 * @CreateTime: 2022/1/9
 */
@Configuration
public class MybatisConfig {

    private static final Logger LOG = LoggerFactory.getLogger(MybatisConfig.class);

    @Autowired
    private Environment env;

    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        String configLocation = env.getProperty("mybatis.config-location");
        String mapperLocation = env.getProperty("mybatis.mapper-locations");
        Resource configResource = this.resolveConfigResource(configLocation);
        Resource[] mapperResources = this.resolveMapperResources(mapperLocation);
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setConfigLocation(configResource);
        sqlSessionFactoryBean.setMapperLocations(mapperResources);
        return sqlSessionFactoryBean.getObject();
    }

    private Resource resolveConfigResource(String configLocation) {
        DefaultResourceLoader resourceLoader = new DefaultResourceLoader();
        return resourceLoader.getResource(configLocation);
    }

    private Resource[] resolveMapperResources(String mapperLocation) {
        ArrayList<Resource> resources = new ArrayList<>();
        ResourcePatternResolver antPathMatcher = new PathMatchingResourcePatternResolver();
        String[] mapperLocations = mapperLocation.split(",");
        try {
            for (String location : mapperLocations) {
                resources.addAll(Arrays.asList(antPathMatcher.getResources(location)));
            }
        } catch (IOException ioe) {
            LOG.warn("读取Mybatis的Mapper文件异常:{}", ioe.getMessage());
        }
        return resources.toArray(new Resource[resources.size()]);
    }
}
